package com.qiao.dfw.loggic.login;

import com.qiao.dfw.config.SpringBeanUtil;
import com.qiao.dfw.dao.PlayerMapper;
import com.qiao.dfw.entity.Player;
import com.qiao.dfw.entity.PlayerLocal;
import com.qiao.dfw.loggic.ATask;
import com.qiao.dfw.loggic.ECode;
import com.qiao.dfw.manager.PlayerManager;
import com.qiao.dfw.network.Connection;
import com.qiao.dfw.network.ConnectionManager;
import com.qiao.dfw.proto.Login;
import com.qiao.dfw.thread.EThreadType;
import com.qiao.dfw.thread.ThreadManager;

import java.util.Objects;

/**
 * @author 乔占江 qq:59663479
 * @version 1.0
 * @date 2024/1/22 2:06
 * @description
 */
public class RegisterTask extends ATask<Login.UserRegisterRequest> {
    @Override
    public void execute0() {

        Player beanPlayerByName = PlayerManager.get(request.getUsername());
        // 没人占用这个账号
        if (beanPlayerByName == null) {
            beanPlayerByName = new Player();
            beanPlayerByName.username = request.getUsername();
            beanPlayerByName.password = request.getPassword();
            beanPlayerByName.nickname = "用户" + 123;
            PlayerManager.add(beanPlayerByName);

            Login.UserRegisterResponse.Builder builder = Login.UserRegisterResponse.newBuilder();
            Login.UserRegisterResponse build = builder.setMsg("注册成功").setSuccess(true).build();

            conn.player = beanPlayerByName;
            conn.player.local = PlayerLocal.Register;

            sendMsg(build.toByteArray());
        } else {
            Login.UserRegisterResponse.Builder builder = Login.UserRegisterResponse.newBuilder();
            Login.UserRegisterResponse build = builder.setMsg("账号已存在").setSuccess(false).build();
            sendMsg(build.toByteArray());

        }


    }

    @Override
    public ECode getCode() {
        return ECode.Register;
    }

    @Override
    public int getThreadIndex() {
        String username = request.getUsername();
        int hash = Objects.hash(username);
        return ThreadManager.getThreadIndex(EThreadType.Login, hash);
    }
}
